<template>
  <div class="login-body">
    <div class="logo-con">
        <h2 class="logo-title color-white">摩塑网管理平台</h2>
    </div>
    <el-card class="login-form-layout">
      <div class="login-title">
        <span :class="isPwd?'hover':''" @click="changeLoginMode('passWord')">账户密码登录</span>
        <span :class="isPwd?'':'hover'" @click="changeLoginMode('code')">验证码登录</span>
      </div>

      <el-form autoComplete="on"  :model="loginForm"  :rules="loginRules"  ref="loginForm"  label-position="left">

        <!--账户密码登录-->
        <div v-if="isPwd">
          <el-form-item prop="username" >
<!--            <el-input  type="text" style="position: fixed;bottom:-99999px" name="username"></el-input>-->
            <el-input name="username" type="text" v-model="loginForm.username"  autoComplete="on" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
<!--            <el-input name="password" :type="pwdType" style="position: fixed;bottom:-99999px"></el-input>-->
            <el-input name="password" :type="pwdType"  @keyup.enter.native="handleLogin"  v-model="loginForm.password"  auto-complete="on"  placeholder="密码">
            <span slot="suffix" @click="showPwd">
              <svg-icon v-show="!pwdType" icon-class="eye-open" class="color-main"></svg-icon>
              <svg-icon v-show="pwdType" icon-class="eye" class="color-main"></svg-icon>
            </span>
            </el-input>
          </el-form-item>
        </div>

        <!--验证码登录-->
        <div v-if="!isPwd">
          <el-form-item prop="phone">
            <el-input name="phone" type="text" v-model="loginForm.phone" autoComplete="off" placeholder="手机号"></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input name="code" type="text" v-model="loginForm.code"  autoComplete="off"  placeholder="验证码" style="width:60%;float:left"></el-input>
            <el-button type="text" style="float:right" @click="handleSendLoginSMSCode" :disabled="sendCode">{{verifyCodeText}}</el-button>
          </el-form-item>
        </div>

        <div class="login-check">
          <el-checkbox v-model="isAgree" style="margin-right:5px"><span>已阅读同意</span></el-checkbox><span class="treaty" @click="dialogVisible=true" style="font-size:12px;color:#409EFF;cursor: pointer">用户使用协议</span>
          <router-link to="/forgetPassword"  class="forgetpwd">忘记密码</router-link>
        </div>
        <el-form-item style="margin-bottom: 60px">
          <el-button style="width: 100%" type="primary" :loading="loading" @click.native.prevent="handleLogin" :disabled="!isAgree">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="ms-footer color-white">
      <p>copyright © {{year}} 泛塑（上海）科技有限公司</p>
    </div>
    <el-dialog
      title="用户使用协议"
      :visible.sync="dialogVisible"
      width="50%">
      <div style="height:400px;overflow: auto">用户使用协议</div>
    </el-dialog>
  </div>



</template>

<script>
  import {isvalidUsername,validatePhone} from '@/utils/validate';
  import {sendLoginSMSCode} from '@/api/login'
  import {setSupport,getSupport,SupportUrl} from '@/utils/support';
  import logo from '@/assets/images/logo.png'
  let md5 = require('md5');
  export default {
    name: 'login',
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!isvalidUsername(value)) {
          callback(new Error('请输入正确的用户名'))
        } else {
          callback()
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value.length < 3) {
          callback(new Error('密码不能小于3位'))
        } else {
          callback()
        }
      };
      const isvalidatePhone = (rule, value, callback) => {
        if(!validatePhone(value)){
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      };
      return {
        isAgree: true,
        sendCode:false,//是否能发送验证码
        dialogVisible:false,
        loginForm: {
          username: '',
          password: '',
          phone:'',
          code:'',
        },
        loginRules: {
          username: [{required: true, trigger: 'blur',message: '请输入用户名'}],
          password: [{required: true, trigger: 'blur', message: '请输入密码'}],
          phone: [{required: true, trigger: 'blur', validator: isvalidatePhone}],
          code: [{required: true, trigger: 'blur', message: '请输入验证码'}],
        },
        loading: false,
        isPwd: true, // 密码登录为true,则为false
        pwdType: 'password',
        logo,
        falg: false, //是否倒计时
        reciprocalTime : null,//倒计时函数
        verifyCodeText:'获取短信验证码',
        timer: 60,//倒计时秒数
        year:(new Date).getFullYear(),
      }
    },
    methods: {
      showPwd() {
        if (this.pwdType === 'password') {
          this.pwdType = ''
        } else {
          this.pwdType = 'password'
        }
      },
      changeText(){
        if(this.loginForm.password === ''){
          this.pwdType = 'text'
        }else{
          this.pwdType = 'password'
        }
      },
      /**
       * 切换登当方式
       * type 'passWord'密码登录，‘code’，验证码登录
       */
      changeLoginMode(type){
        this.isPwd = type == 'passWord';
        this.$refs['loginForm'].resetFields();
      },

      /**
       * 发送验证码
       */
      handleSendLoginSMSCode(){
        if(!validatePhone(this.loginForm.phone)){
          this.$message({
            message: '请输入正确的手号！',
            type: 'warning',
            duration: 1000
          });
          return
        }
        this.sendCode = true;
        let encryption =  md5(this.loginForm.phone + 'moresu.,!');
        console.log(encryption)
          sendLoginSMSCode({mobile:this.loginForm.phone,encryption,apiId:'ADMINWEB'}).then(()=>{
            this.$message({
              message: '验证码已送',
              type: 'success',
              duration: 1000
            });
            this.showCountDown();
          }).catch(()=>{
            this.sendCode = false;
          })

      },
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            this.$store.dispatch('Login', {data:this.loginForm,isPwd:this.isPwd}).then(() => {
              this.loading = false;
              this.$router.push({path: '/'})
            }).catch((err) => {
              this.loading = false;
              if(err.code == '123456'){
                this.$router.push({path: '/forgetPassword'})
              }
            })
          } else {
            console.log('参数验证不合法！');
            return false
          }
        })
      },

      /**
       * 倒计时
       * @return null
       */
      showCountDown () {
        this.verifyCodeText = this.timer + '秒后重新获取';
        this.falg = true;
        let self = this;
        self.reciprocalTime = function(time){
          //@ts-ignore : js setTimeout
          setTimeout(function(){
            if(time >=1 && self.falg){
              time--;
              self.verifyCodeText=time + '秒后重新获取';
              self.reciprocalTime(time);
            }else{

              self.verifyCodeText='获取短信验证码';
              self.sendCode = false;
              //@ts-ignore : js clearTimeout
              clearTimeout(self.reciprocalTime);
            }
          },1000);
        };
        self.reciprocalTime(this.timer);
      },

    }
  }
</script>

<style scoped>
  @font-face {
    font-family: 'password';
    src: url(./PasswordEntry.ttf);
  }
  .logo-title {
    text-align: center;
  }
  .logo-img{
    background: #fff;
    border-radius: 50%;
    width: 100px;
    height: 100px;
    text-align: center;
    margin: 0 auto
  }
  .login-body{
    background: url('../../assets/images/bg.jpg');
    background-size: cover;
    min-height: 100%;
    padding-top: 5%
  }
  .logo-img img{
    width: 66px;
    margin: 10px auto
  }
  .login-form-layout {
    width: 360px;
    margin: 20px auto;
  }

  .login-title{
    margin: 10px auto 40px;
    border-bottom: 1px solid #ddd;
  }

  .login-title span{
    display: inline-block;
    padding: 20px;
    cursor: pointer;
  }

  .login-title span.hover{
    border-bottom: 3px solid #1890FF;
  }

  .login-check{
    margin: 10px auto 20px;
    padding-left: 2px;
  }

  .login-center-layout {
    background: #409EFF;
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    margin-top: 200px;
  }

  .forgetpwd{
    float: right;
    font-size: 14px;
    color: #999
  }

  .treaty{
    text-decoration: underline
  }

  .ms-footer{
    padding: 50px 0;
    text-align: center
  }

  .ms-footer h3{
    font-size: 30px;
    font-weight: normal
  }

  .ms-footer p{
    font-size: 12px
  }
</style>
